---------------------------------------
--This module does the following: when the signal reset_req becomes high it watchs the ADC_ampl input, and as soon as the value of this input becomes higher than a predefined value, it puts the reset_counter signal to high
--
--Oussama Chammam, IC-control-localization-project team
--KTH, MF2063
--last edit: 2012-11-15
----------------------------------------

library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;
use ieee.std_logic_unsigned.all;
use ieee.std_logic_arith.all;
----------------------------------------

entity counter_resetter is
	port(	ADC_ampl: in std_logic_vector(11 downto 0);  	--from external ADC
			clk : in std_logic;
			reset : in std_logic;
			reset_req : in std_logic;						--is high when the MCU requests restting the counter
			reset_counter: out std_logic					--connected to the counter's reset input
	);
end counter_resetter;  

----------------------------------------



architecture behaviour of counter_resetter is

constant high_level_limit : std_logic_vector(11 downto 0) := x"008";		--this constant is tuned so that we have a suitable threshold to detect a logical "high" signal coming from the RF (we run ON-OFF keying)

signal request_asked : std_logic;

begin

    process(clk, reset)
    begin
		if reset = '1' then 				--assynchronous reset
			reset_counter <= '1';  			--do not reset counter
											--is the reset signal in the counter active low???
			request_asked <= '0';			--no reset was requested
		elsif rising_edge(clk) then
			if (reset_req = '1' and request_asked = '0') then
				request_asked <= '1';		-- counter reset is requested -> flag that
			elsif (request_asked = '1') then
				if (ADC_ampl > high_level_limit) then
					-- FUTURE work: check for three consecutive ADC_ampl values that exceeds high_level_limit in order to become sure that what we recieved is actually a valid pulse and not just a noise
					request_asked <= '0';	--reset counter is performed -> reset the request flag
					reset_counter <= '0';  	--is the reset signal in the counter active low???
				end if;
			end if;
		end if;
    end process;

end behaviour;


------------------------------------------
